package logic

import (
	"context"
	"customer/model/mysql"
	"customer/model/redis"
	"customer/pkg"
	"customer/userrpc/internal/svc"
	"customer/userrpc/userrpc"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmsregister" + in.Tel)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	cmd := redis.Client.Get("captcharegister" + in.Account)
	if cmd.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("Account=?", in.Account).Find(&findUser)
	if findUser.ID != 0 {
		return nil, fmt.Errorf("该账号已被注册，请重新输入")
	}
	if findUser.Tel == in.Tel {
		return nil, fmt.Errorf("该手机号已被注册，请重新输入")
	}
	user := mysql.User{
		Account:  in.Account,
		Password: pkg.PwdMd5(in.Password),
		Tel:      in.Tel,
	}
	mysql.DB.Debug().Create(&user)

	redis.Client.Del("sendSmsregister" + in.Tel)
	redis.Client.Del("captcharegister" + in.Account)

	return &userrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
